import { Component, OnInit } from '@angular/core';
import { PageEntity } from '../../../../core/domain/page.entity';
import { StatusEnum } from '../../../../core/enum/status.enum';
import { OtherUtil } from '../../../../utils/other.util';
import { FilterEnum, FilterTypeEnum } from '../../../../core/enum/filter.enum';
import { NzMessageService } from 'ng-zorro-antd';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { SupervisionEvaluteformService } from './supervision-evaluteform.service';
import { PaginationUtils } from '../../../../utils/paginationUtils';
import { Response } from '../../../../core/domain/response';

@Component({
  selector: 'app-supervision-evaluteform',
  templateUrl: './supervision-evaluteform.component.html',
  styleUrls: ['./supervision-evaluteform.component.scss'],
  providers: [SupervisionEvaluteformService]
})
export class SupervisionEvaluteformComponent implements OnInit {
  yearname = null;
  semestername = null;
  formname = null;
  pageInfo: PageEntity = new PageEntity();
  allList = [];
  displayList: Array<any> = [];
  mapOfCheckedId: { [key: string]: boolean } = {};
  isAllCheck = false;
  isIndeterminate = false;
  canDelete = false;
  yearListSearch = [];
  semestSearch = [];

  // 新增
  isVisible = false;
  validateForm: FormGroup;
  addObj: AddObj = new AddObj();
  yearList = []; // 学年
  semesterList = [];
  collogeList = [];
  isEdit = false;

  mainStatus = 1; // 1.显示主页面，2.显示新增页面,3:发布评价

  // 编辑
  currId = null;
  sortTreeList = [];
  classifyList = [];
  activeId = null;
  showPage = false; // 是否不显示右边界面,默认显示

  isVisibleXm = false; // 新增评价项目
  validateFormXm: FormGroup;
  xmObj: XmObj = new XmObj();

  // 要点
  nameYd = null;
  pageInfoYd: PageEntity = new PageEntity();
  allListYd = [];
  displayListYd: Array<any> = [];
  mapOfCheckedIdYd: { [key: string]: boolean } = {};
  isAllCheckYd = false;
  isIndeterminateYd = false;
  canDeleteYd = false;
  validateFormYd: FormGroup;
  ydObj: YdObj = new YdObj();
  isVisibleYd = false;

  previewObj = null; // 预览
  isPreview = true; // 预览true,下载false

  constructor(
    private service: SupervisionEvaluteformService,
    private message: NzMessageService,
    private fb: FormBuilder
  ) { }

  ngOnInit() {
    this.initForm();
    this.getYearSearch();
    this.page(this.pageInfo);
    this.initFormXm();
    this.initFormYd();
  }

  initForm() {
    this.validateForm = this.fb.group({
      schoolYear: [this.addObj.schoolYear, [Validators.required]],
      semesterId: [this.addObj.semesterId, [Validators.required]],
      name: [this.addObj.name, [Validators.required]]
    });
  }

  initFormXm() {
    this.validateFormXm = this.fb.group({
      name: [this.xmObj.name, [Validators.required]],
      isDetail: [this.xmObj.isDetail, [Validators.required]],
      isScore: [this.xmObj.isScore, [Validators.required]],
      score: [this.xmObj.score, []]
    });
  }

  initFormYd() {
    this.validateFormYd = this.fb.group({
      classifyId: [this.ydObj.classifyId, [Validators.required]],
      name: [this.ydObj.name, [Validators.required]],
      type: [this.ydObj.type, [Validators.required]],
      value: [this.ydObj.value, []],
      value1: [this.ydObj.value, []]
    });
  }

  /**
   * 查询学年学期列表
   */
  getYearSearch() {
    this.service.year().subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.yearListSearch = res.datas;
        this.semestSearch = [];
      }
    });
  }

  yearSearchChange(e) {
    this.semestername = null;
    this.yearListSearch.forEach(item => {
      if (e == item.schoolYear) {
        this.semestSearch = item.semester;
      }
    });
  }

  /*****分页查询*********/
  page(page: PageEntity): void {
    page.filters['type'.toString()] = PaginationUtils.filters('校级督导', FilterEnum.EQUALS);
    page.multiSortMeta = [
      {
        field: 'gmtCreate',
        order: -1
      }
    ];
    this.service.page(page).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.allList = res.datas.data;
        this.pageInfo.totalRecords = res.datas.totalRecords;
      }
    });
  }


  /*******第几页*******/
  searchPageIndex(event: any) {
    this.pageInfo.first = event;
    this.page(this.pageInfo);
  }

  /*******每页几条*****/
  searchPageSize(event: any) {
    this.pageInfo.rows = event;
    this.pageInfo.first = 1;
    this.page(this.pageInfo);
  }

  currentPageDataChange($event): void {
    this.displayList = $event;
    this.refreshStatus();
  }

  /*******状态改变******/
  refreshStatus(): void {
    this.isAllCheck = this.displayList.every(item => this.mapOfCheckedId[item.id]);
    this.isIndeterminate =
      this.displayList.some(item => this.mapOfCheckedId[item.id]) &&
      !this.isAllCheck;
    this.checkDelete();
  }

  /**
   * 全选
   * @param value： value
   */
  checkAll(value: boolean): void {
    this.displayList.forEach(item => (this.mapOfCheckedId[item.id] = value));
    this.refreshStatus();
  }

  /**
   * 主页根据id删除逻辑
   */
  delByIdsLogic() {
    const arr = [];
    for (const val in this.mapOfCheckedId) {
      if (this.mapOfCheckedId[val]) {
        arr[arr.length] = val;
      }
    }
    return arr;
  }

  moveCloseFn(): void {
    this.mapOfCheckedId = {};
    this.canDelete = true;
    this.isAllCheck = false;
  }

  /******删除所选********/
  deleteAll() {
    const arr = this.delByIdsLogic();
    if (arr.length < 1) {
      this.message.warning('请勾选要删除的数据！');
      return;
    }
    this.service.deleteAll(arr).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.mapOfCheckedId = {};
        this.pageInfo.first = 1;
        this.message.success(res.message);
        this.page(this.pageInfo);
      }
    });
  }


  /**
   * 点击删除一个
   * @param ids： id
   */
  deleteOne(ids: string) {
    this.service.delete(ids).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.mapOfCheckedId = {};
        this.message.success(res.message);
        this.page(this.pageInfo);
      }
    });
  }

  /********判断是否选择了数据需要删除**********/
  checkDelete(): void {
    this.canDelete = OtherUtil.deleteIds(this.mapOfCheckedId).length <= 0;
  }

  /*******点击查询*********/
  clickSearch() {
    this.pageInfo.first = 1;
    this.formname ? this.pageInfo.filters['name'.toString()] = PaginationUtils.filters(this.formname, FilterEnum.CONTAINS) : delete this.pageInfo.filters['name'.toString()];
    this.yearname ? this.pageInfo.filters['schoolYear'.toString()] = PaginationUtils.filters(this.yearname, FilterEnum.EQUALS) : delete this.pageInfo.filters['schoolYear'.toString()];
    this.semestername ? this.pageInfo.filters['semesterId'.toString()] = PaginationUtils.filters(this.semestername, FilterEnum.EQUALS) : delete this.pageInfo.filters['semesterId'.toString()];
    this.page(this.pageInfo);
  }

  /********点击重置**************/
  resetSearch() {
    this.formname = null;
    this.yearname = null;
    this.semestername = null;
    this.semestSearch = [];
    this.pageInfo.first = 1;
    delete this.pageInfo.filters['name'.toString()];
    delete this.pageInfo.filters['schoolYear'.toString()];
    delete this.pageInfo.filters['semesterId'.toString()];
    this.page(this.pageInfo);
  }

  clickAdd() {
    this.addObj = new AddObj();
    this.getYearSemes();
    // this.getColleges();
    this.isVisible = true;
    this.initForm();
  }

  /**
   * 查询学年学期列表
   */
  getYearSemes() {
    this.service.year().subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.yearList = res.datas;
        if (this.isEdit) { // 编辑时
          this.yearList.forEach(item => {
            if (this.addObj.schoolYear == item.schoolYear) {
              this.semesterList = item.semester;
            }
          });
        } else {
          this.semesterList = [];
        }
      }
    });
  }

  yearListChange(e) {
    if (this.isEdit) { // 编辑时,进入页面时不需要清空值
    } else {
      this.addObj.semesterId = null;
      this.yearList.forEach(item => {
        if (e == item.schoolYear) {
          this.semesterList = item.semester;
        }
      });
    }
  }

  semesterChange(e) {
    if (this.isEdit) { // 编辑时,进入页面时不需要清空值
    } else {
      this.addObj.semester = null;
      this.semesterList.forEach(item => {
        if (e == item.id) {
          this.addObj.semester = item.semester;
        }
      });
    }
  }

  /**
   * 查询学院
   */
  getColleges() {
    this.service.getCollege().subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.collogeList = res.datas;
      }
    });
  }


  // 新增编辑保存
  submit() {
    this.addObj.type = '校级督导';
    const opt = this.addObj.id ? 'update' : 'create';
    this.service[opt](this.addObj).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.message.success(res.message);
        this.isVisible = false;
        this.page(this.pageInfo);
      }
    });
  }

  // 预览
  preview(data) {
    this.isPreview = true;
    this.service.buildExam({id: data.id}).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.previewObj = res.datas;
        this.previewObj['list1'.toString()] = [];
        this.previewObj['sumScore'.toString()] = null;
        if (this.previewObj.classifyList && this.previewObj.classifyList.length > 0) {
          const arry = [];
          this.previewObj.classifyList.forEach(item => {
            item['itemScore'.toString()] = null;
            item['isType'.toString()] = null;
            if (item.itemList && item.itemList.length > 0) {
              item.isType = 1;
              item.itemList.forEach((list, index) => {
                const obj = JSON.parse(JSON.stringify(item));
                obj['sub_examClassifyId'.toString()] = list.examClassifyId;
                obj['sub_id'.toString()] = list.id;
                obj['sub_name'.toString()] = list.name;
                obj['sub_type'.toString()] = list.type;
                obj['sub_value'.toString()] = list.value;
                obj['sub_defvalue'.toString()] = null;
                obj['sub_input'.toString()] = false;
                if (list.value) {
                  obj['sub_valueList'.toString()] = list.value.split('/');
                } else {
                  obj['sub_valueList'.toString()] = [];
                }
                obj['rows'.toString()] = item.itemList.length;
                obj['isshow'.toString()] = index === 0;
                arry.push(obj);
              });
            } else {
              item.isType = 2;
              arry.push(item);
            }
          });
          this.previewObj.list1 = arry;
        }
        this.mainStatus = 3;
      }
    });
  }

  multChange(e, data) {
    if (e && e.length > 0) {
      if (e.indexOf('其他') == -1 && e.indexOf('其它') == -1) { // 不存在
        data.sub_input = false;
      } else {
        data.sub_input = true;
      }
    }
  }

  singleChange(e, data) {
    if (e) {
      if (e == '其他' || e == '其它') { // 不存在
        data.sub_input = true;
      } else {
        data.sub_input = false;
      }
    }
  }

  sums(e) {
    if (e) {
      let sum = 0;
      this.previewObj.list1.forEach(item => {
        if (item.isshow || item.isType == 2) {
          if (item.itemScore) {
            sum += Number(item.itemScore);
          }
        }
      });
      this.previewObj.sumScore = sum;
    }
  }


  edit(data) {
    this.mainStatus = 2;
    this.currId = data.id;
    this.getTrees();
    this.pageInfoYd = new PageEntity();
  }

  backXm() {
    this.mainStatus = 1;
    this.currId = null;
  }

  /**
   * 获取分类
   */
  getTrees() {
    this.service.getTree({id: this.currId}).subscribe((res: Response) => {
      const {datas, status} = res;
      if (status === StatusEnum.SUCCESS) {
        this.classifyList = datas;
        this.sortTreeList = datas;
        if (this.sortTreeList.length > 0) {
          this.activeId = this.sortTreeList[0].id;
          this.showPage = this.sortTreeList[0].isDetail == 0;
        }
        this.pageYd(this.pageInfoYd);
      }
    });
  }

  // 评价项目新增
  xmAdd() {
    this.initFormXm();
    this.xmObj = new XmObj();
    this.isVisibleXm = true;
  }

  xmEdit(data) {
    this.xmObj = JSON.parse(JSON.stringify(data));
    this.initFormXm();
    this.isVisibleXm = true;
  }

  submitXm() {
    if (this.xmObj.isScore == 1) {
      if (!this.xmObj.score) {
        this.message.warning('选择设置分数时，分数必填!');
        return;
      }
    }
    this.xmObj['superviseId'.toString()] = this.currId;
    const opt = this.xmObj.id ? 'sortUpdate' : 'sortCreat';
    this.service[opt](this.xmObj).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.message.success(res.message);
        this.isVisibleXm = false;
        this.getTrees();
      }
    });
  }

  xmDel(data) {
    this.service.sortDelete({id: data.id}).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.message.success(res.message);
        this.getTrees();
      }
    });
  }

  clickTabs(data) {
    this.activeId = data.id;
    this.resetSearchYd();
    this.moveCloseFnYd();
    this.showPage = data.isDetail == 0;
  }

  /*****分页查询*********/
  pageYd(page: PageEntity): void {
    this.pageInfoYd.filters['classifyId'.toString()] = PaginationUtils.filters(this.activeId, FilterEnum.EQUALS);
    this.pageInfoYd.filters['superviseId'.toString()] = PaginationUtils.filters(this.currId, FilterEnum.EQUALS);
    this.service.itemPage(page).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.allListYd = res.datas.data;
        this.pageInfoYd.totalRecords = res.datas.totalRecords;
      }
    });
  }

  currentPageDataChangeYd($event): void {
    this.displayListYd = $event;
    this.refreshStatusYd();
  }

  /*******状态改变******/
  refreshStatusYd(): void {
    this.isAllCheckYd = this.displayListYd.every(item => this.mapOfCheckedIdYd[item.id]);
    this.isIndeterminateYd =
      this.displayListYd.some(item => this.mapOfCheckedIdYd[item.id]) &&
      !this.isAllCheckYd;
    this.checkDeleteYd();
  }

  /**
   * 全选
   * @param value： value
   */
  checkAllYd(value: boolean): void {
    this.displayListYd.forEach(item => (this.mapOfCheckedIdYd[item.id] = value));
    this.refreshStatusYd();
  }

  moveCloseFnYd(): void {
    this.mapOfCheckedIdYd = {};
    this.canDeleteYd = false;
    this.isAllCheckYd = false;
  }

  /******删除所选********/
  deleteAllYd() {
    const arr = [];
    for (const val in this.mapOfCheckedIdYd) {
      if (this.mapOfCheckedIdYd[val]) {
        arr[arr.length] = val;
      }
    }
    if (arr.length < 1) {
      this.message.warning('请勾选要删除的数据！');
      return;
    }
    this.service.deleteAll(arr).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.mapOfCheckedIdYd = {};
        this.pageInfoYd.first = 1;
        this.message.success(res.message);
        this.pageYd(this.pageInfoYd);
      }
    });
  }


  /**
   * 点击删除一个
   * @param ids： id
   */
  deleteOneYd(ids: string) {
    this.service.itemDelete({id: ids}).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.mapOfCheckedIdYd = {};
        this.message.success(res.message);
        this.pageYd(this.pageInfoYd);
      }
    });
  }

  /********判断是否选择了数据需要删除**********/
  checkDeleteYd(): void {
    this.canDeleteYd = OtherUtil.deleteIds(this.mapOfCheckedIdYd).length <= 0;
  }

  /*******点击查询*********/
  clickSearchYd() {
    this.pageInfoYd.first = 1;
    this.nameYd ? this.pageInfoYd.filters['name'.toString()] = PaginationUtils.filters(this.nameYd, FilterEnum.CONTAINS) : delete this.pageInfoYd.filters['name'.toString()];
    this.pageYd(this.pageInfoYd);
  }

  /********点击重置**************/
  resetSearchYd() {
    this.nameYd = null;
    this.pageInfoYd.first = 1;
    delete this.pageInfoYd.filters['name'.toString()];
    this.pageYd(this.pageInfoYd);
  }

  clickAddYd() {
    this.ydObj = new YdObj();
    this.ydObj['superviseId'.toString()] = this.currId;
    this.initFormYd();
    this.isVisibleYd = true;
  }

  editYd(data) {
    this.ydObj = JSON.parse(JSON.stringify(data));
    this.initFormYd();
    this.isVisibleYd = true;
  }

  submitYd() {
    if (this.ydObj.type != '文本框') {
      if (!this.ydObj.value) {
        this.message.warning('类型不为文本框时，评价记录必须填写!');
        return;
      }
    } else {
      this.ydObj.value = null;
    }
    const opt = this.ydObj.id ? 'itemUpdate' : 'itemCreat';
    this.service[opt](this.ydObj).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.message.success(res.message);
        this.isVisibleYd = false;
        this.pageYd(this.pageInfoYd);
      }
    });
  }


  /**
   * 下载
   */
  downLoad(rid) {
    this.isPreview = false;
    this.service.buildExam({id: rid}).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.previewObj = res.datas;
        this.previewObj['list1'.toString()] = [];
        this.previewObj['sumScore'.toString()] = null;
        if (this.previewObj.classifyList && this.previewObj.classifyList.length > 0) {
          const arry = [];
          this.previewObj.classifyList.forEach(item => {
            item['itemScore'.toString()] = null;
            item['isType'.toString()] = null;
            if (item.itemList && item.itemList.length > 0) {
              item.isType = 1;
              item.itemList.forEach((list, index) => {
                const obj = JSON.parse(JSON.stringify(item));
                obj['sub_examClassifyId'.toString()] = list.examClassifyId;
                obj['sub_id'.toString()] = list.id;
                obj['sub_name'.toString()] = list.name;
                obj['sub_type'.toString()] = list.type;
                obj['sub_value'.toString()] = list.value;
                obj['sub_defvalue'.toString()] = null;
                obj['sub_input'.toString()] = false;
                if (list.value) {
                  obj['sub_valueList'.toString()] = list.value.split('/');
                } else {
                  obj['sub_valueList'.toString()] = [];
                }
                obj['rows'.toString()] = item.itemList.length;
                obj['isshow'.toString()] = index === 0;
                arry.push(obj);
              });
            } else {
              item.isType = 2;
              arry.push(item);
            }
          });
          this.previewObj.list1 = arry;
        }
        setTimeout(() => {
          this.downfile();
        }, 1000);
      }
    });
  }

  downfile() {
    const printContent = document.getElementById('report');
    const WindowPrt = window.open('', '', 'left=0,top=0,toolbar=0,scrollbars=0,status=0');
    WindowPrt.document.write(printContent.innerHTML);
    WindowPrt.document.close();
    WindowPrt.focus();
    WindowPrt.print();
    WindowPrt.close();
  }


  scoreSet(e) {
    if (e == 0) { // 不设置分数，默认无评价要点，评价要点不能选择
      this.xmObj.isDetail = 0;
    }
  }


}

class AddObj {
  deptId?: string;
  id?: string;
  name?: string;
  schoolYear?: string;
  semester?: string;
  semesterId?: string;
  superviseId?: string; // 系部督导需要的校级督导的id
  type?: string; // 类型：校级督导、系部督导
}

class XmObj {
  id?: string;
  name?: string;
  score?: number;
  isScore?: any;
  isDetail?: any;
}

class YdObj {
  classifyId?: string;
  id?: string;
  name?: string;
  type?: string; // 值类型：多选，单选，文本
  value?: string; // 值类型：多选，单选，文本
}
